package main

import (
    "os"
	"fmt"
	"time"
    "dhfshop/models/misc"
	"dhfshop/models/org"
	"dhfshop/models/consts"
	"dhfshop/models/isv"
	"dhfshop/models/preorder"
	"dhfshop/utils/uuid"
	_ "dhfshop/routers"
	_ "dhfshop/task"       // run cron task 
    "regexp"
	"dhfshop/service/event"
	"dhfshop/service/authz"
	"dhfshop/service/redisgo"
	"dhfshop/service/nsqcli"
	//"dhfshop/service/ledisdb"
	"dhfshop/service/wscom"
	"dhfshop/controllers/shopping"
	"dhfshop/controllers/reauthorize"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/plugins/cors"
	"github.com/astaxie/beego/orm"
	_ "github.com/astaxie/beego/session/mysql"
	_ "github.com/astaxie/beego/session/redis"
	_ "github.com/go-sql-driver/mysql"
	"dhfshop/utils/response"
	"dhfshop/domain/nsqproc"
	"dhfshop/domain/im"
	"dhfshop/service/gcpool"
	"dhfshop/service/timer"
)

var (
	authHeaderSchemeRe = regexp.MustCompile("^Bearer$")
	LogPath string = "log"
)

func subscribeInit() {
	shopping.TradeEventInit()
	shopping.ReturnEventInit()
}

func adminWxAppInit() {
    refreshToken, _:= beego.AppConfig.Bool("RefreshToken")
	if !refreshToken{
	    return
	}
    sellerAppID := beego.AppConfig.String("SellerAppID")
	if _, err := isv.GetAuthorizeByAppId(sellerAppID); err == orm.ErrNoRows {
		m := new(isv.Authorize)
		m.TypeId = 1
		m.AppId = sellerAppID
		m.AccessToken = ""
		m.ExpiresIn = 0
		isv.AddAuthorize(m)
	}
}

func init() {
    orm.RegisterDriver("mysql", orm.DRMySQL)
	dbAddress := beego.AppConfig.String("DbAddress")
	orm.RegisterDataBase("default", "mysql", dbAddress)
    orm.DefaultTimeLoc = time.UTC    //注意
	//beego.BConfig.Listen.EnableAdmin = true
	beego.BeeLogger.Async()
    beego.BeeLogger.EnableFuncCallDepth(true)
    if _, err := os.Stat(LogPath); os.IsNotExist(err) {
		os.Mkdir(LogPath, 0777)
	}
	cfg := fmt.Sprintf(`{"filename":"%s"}`, LogPath + "/" + beego.BConfig.AppName + ".log")
    beego.BeeLogger.SetLogger("file", cfg)
	beego.SetLevel(beego.LevelDebug)
	//
	response.LangConf = response.NewConfig("conf/lang_zh.json")  //错误提示文件
	wscom.ReceiveSvr = wscom.NewReceiveSvr()           //接受handle
	wscom.ConnectHub = wscom.NewConnectHub()           //ws连接池
	imlayer.PushMsgSvrIns = imlayer.NewPushMsgSvr()             //微信推送消息池
}

func main() {
    beego.SetStaticPath("/web", "web")
	beego.SetStaticPath("/views", "views")
	beego.SetStaticPath("/static", "static")
	//自动建表
	if beego.BConfig.RunMode == "prod" {
		orm.Debug = false
		if err := orm.RunSyncdb("default", false, false); err != nil {
		    beego.Debug(err.Error())
		}
	} else {
		orm.Debug = true
		if err := orm.RunSyncdb("default", false, true); err != nil {
		    beego.Debug(err.Error())
		}
		if beego.BConfig.WebConfig.EnableDocs {
			beego.BConfig.WebConfig.DirectoryIndex = true
			beego.SetStaticPath("/swagger", "swagger")
		}
	}
	isv.InitDefaultManager("dhfadmin", "dhf123456789")
	misc.InitDefaultAreas(consts.Area)
	uuid.InitWorker(1)
    org.InitAllResource("conf/resource.json")
	reauthorize.InitTopUrl("conf/reauthorize.json")
	event.EventInit()
	subscribeInit()
	adminWxAppInit()
	preorder.InitPubTemplate()
    //
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
        AllowAllOrigins:  true,
        AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
        AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "dhfbackstoreid"},
        ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
        AllowCredentials: true,
    }))
	if err := authz.StartAuthz("model.conf", "policy.csv"); err != nil {
	    beego.Debug(err.Error())
		return
	}
	redisPwd := ""
	redisServer := beego.AppConfig.String("redisServer")
	enableRedisPwd, _:= beego.AppConfig.Bool("EnableRedisPwd")
	if enableRedisPwd {
	    redisPwd = beego.AppConfig.String("RedisPwd")
	}
	redisgo.New(redisServer, redisPwd, 0)   //db = 0
	//
	nsqUrl := beego.AppConfig.String("NsqUrl")
	nsqTmpTopic := beego.AppConfig.String("NsqTmpTopic")
	nsqcli.ConsumerRegister(nsqUrl,nsqTmpTopic,nsqTmpTopic,nsqproc.NsqRegisterFunc)
	nsqTimerTopic := beego.AppConfig.String("NsqTimerTopic")
	nsqcli.ConsumerRegister(nsqUrl,nsqTimerTopic,nsqTimerTopic,nsqproc.NsqRegisterTimerFunc)
	go wscom.ConnectHub.Run()
	go wscom.ReceiveSvr.Run()
	// ------------- 关键 -------------------- // 
	gcpool.GO_CONN_POOL = gcpool.NewPool() // 创建对象
	gcpool.GO_CONN_POOL.Register("default") // 注册连接池
	gcpool.GO_CONN_POOL.Start() // 启动服务
	// ------------- -- -------------------- // 
	timer.NewGrapeTimer()
	go imlayer.PushMsgSvrIns.Run()
	beego.Run()
}
